package com.fw.ui.view.settings.usercontrol.bouser.event;

import static org.springframework.beans.factory.config.BeanDefinition.SCOPE_PROTOTYPE;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.fw.service.bean.ErrorBean;
import com.fw.service.bouser.bean.BOUserBean;
import com.fw.ui.ApplicationUI;
import com.fw.ui.bao.BOUserBAO;
import com.fw.ui.bao.MessageBAO;
import com.fw.ui.util.SessionInfoUtils;
import com.fw.ui.util.UICommonUtils;
import com.fw.ui.util.VaadinApplicationObjectSupport;
import com.fw.ui.view.common.ConfirmDialogWindow;
import com.fw.ui.view.event.AbstractButtonClickListener;
import com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView;
import com.vaadin.ui.Button.ClickEvent;

@Component
@Scope(SCOPE_PROTOTYPE)
public class CreateBOUserSaveButtonClickListener extends AbstractButtonClickListener {

    private static final long serialVersionUID = 482478998438351054L;

    @Autowired
    protected transient VaadinApplicationObjectSupport app;
    @Autowired
    private BOUserBAO bOUserBAO;
    @Autowired
    private MessageBAO messageBAO;
    @Autowired
    private UICommonUtils uiCommonUtils;
    @Autowired
    private SessionInfoUtils sessionInfoUtils;

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> click(ClickEvent event) throws Exception {
	CreateBOUserView createBOUserView = (CreateBOUserView) this.getBasedComponent();

	String email = createBOUserView.getTxtEmail().getValue();
	String employeeId = createBOUserView.getTxtEmployeeId().getValue();
	String employeeName = createBOUserView.getTxtEmployeeName().getValue();
	String username = createBOUserView.getTxtUsername().getValue();
	Long roleId = (Long) createBOUserView.getCbbGroup().getValue();
	String roleName = (String) createBOUserView.getCbbGroup().getItemCaption(roleId);

	BOUserBean boUserBean = new BOUserBean();
	boUserBean.setEmail(email);
	boUserBean.setEmployeeID(employeeId);
	boUserBean.setEmployeeName(employeeName);
	boUserBean.setRole(roleName);
	boUserBean.setId(null);
	boUserBean.setUsername(username);

	ApplicationUI applicationUI = (ApplicationUI) createBOUserView.getUI();
	sessionInfoUtils.setSessionInfoDetails(boUserBean, applicationUI.getAuthenticationBean(), applicationUI.getLocale());

	Map<String, Serializable> mapResult = this.bOUserBAO.createBOUser(boUserBean);
	Map<String, Object> result = new HashMap<String, Object>();
	if (mapResult != null) {
	    List<ErrorBean> errorBeans = (List<ErrorBean>) mapResult.get(List.class.getName() + "." + ErrorBean.class.getName());
	    BOUserBean userBean = (BOUserBean) mapResult.get(BOUserBean.class.getName());
	    if (errorBeans != null && !errorBeans.isEmpty()) {
		result.put(MessageBAO.MESSAGE_WARNING_TYPE, errorBeans);
	    } else {
		if (userBean != null && userBean.getId() != null) {

		    uiCommonUtils.clearAllUIComponentWithPrefixDefaultValue(createBOUserView, null);

		    String title = messageBAO.getMessage("message.dialog.title.info");
		    String[] params = new String[] { userBean.getPassword() };
		    String content = messageBAO.getMessageWithParams("com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView.message.created", params);
		    String okCaption = messageBAO.getMessage("application.button.ok.caption");

		    ConfirmDialogWindow.createConfirmDialog(createBOUserView.getUI(), title, content, okCaption, null, "150px", "500px");

		    return null;
		} else {
		    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView.message.failed");
		}
	    }
	} else {
	    result.put(MessageBAO.MESSAGE_WARNING_TYPE, "message.error.common");
	}
	return result;
    }

    @Override
    public boolean validate(ClickEvent event) {
	CreateBOUserView createBOUserView = (CreateBOUserView) this.getBasedComponent();
	try {

	    uiCommonUtils.clearAllUIComponentNoInputFieldWithPrefix(createBOUserView);

	    boolean usernameValid = createBOUserView.getTxtUsername().isValid();
	    boolean emailValid = createBOUserView.getTxtEmail().isValid();
	    boolean employeeIdValid = createBOUserView.getTxtEmployeeId().isValid();
	    boolean employeeNameValid = createBOUserView.getTxtEmployeeName().isValid();
	    boolean groupValid = createBOUserView.getCbbGroup().isValid();

	    if (usernameValid && emailValid && employeeIdValid && employeeNameValid && groupValid) {
		Boolean isUnique = this.bOUserBAO.checkUniqueUsername(createBOUserView.getTxtUsername().getValue());
		if (isUnique == null || !isUnique.booleanValue()) {
		    createBOUserView.getTxtUsername().addStyleName("v-textfield-error");
		    createBOUserView.getLblUsernameValidateMessage().setValue(
			    this.messageBAO.getMessage("com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView.message.username.exist"));
		    createBOUserView.getRow1Validate().setVisible(true);
		    return false;
		}
		return true;
	    } else {
		if (!usernameValid) {
		    createBOUserView.getTxtUsername().addStyleName("v-textfield-error");
		    if (createBOUserView.getTxtUsername().getErrorMessage() != null) {
			createBOUserView.getLblUsernameValidateMessage().setValue(
				createBOUserView.getTxtUsername().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createBOUserView.getRow1Validate().setVisible(true);
		} else {
		    Boolean isUnique = this.bOUserBAO.checkUniqueUsername(createBOUserView.getTxtUsername().getValue());
		    if (isUnique == null || !isUnique.booleanValue()) {
			createBOUserView.getTxtUsername().addStyleName("v-textfield-error");
			createBOUserView.getLblUsernameValidateMessage().setValue(
				this.messageBAO.getMessage("com.fw.ui.view.settings.usercontrol.bouser.CreateBOUserView.message.username.exist"));
			createBOUserView.getRow1Validate().setVisible(true);
		    }
		}

		if (!emailValid) {
		    createBOUserView.getTxtEmail().addStyleName("v-textfield-error");
		    if (createBOUserView.getTxtEmail().getErrorMessage() != null) {
			createBOUserView.getLblEmailValidateMessage().setValue(
				createBOUserView.getTxtEmail().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createBOUserView.getRow2Validate().setVisible(true);
		}

		if (!employeeIdValid) {
		    createBOUserView.getTxtEmployeeId().addStyleName("v-textfield-error");
		    if (createBOUserView.getTxtEmployeeId().getErrorMessage() != null) {
			createBOUserView.getLblEmployeeIdValidateMessage().setValue(
				createBOUserView.getTxtEmployeeId().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createBOUserView.getRow4Validate().setVisible(true);
		}

		if (!employeeNameValid) {
		    createBOUserView.getTxtEmployeeName().addStyleName("v-textfield-error");
		    if (createBOUserView.getTxtEmployeeName().getErrorMessage() != null) {
			createBOUserView.getLblEmployeeNameValidateMessage().setValue(
				createBOUserView.getTxtEmployeeName().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createBOUserView.getRow5Validate().setVisible(true);
		}

		if (!groupValid) {
		    createBOUserView.getCbbGroup().addStyleName("v-filterselect-error");
		    if (createBOUserView.getCbbGroup().getErrorMessage() != null) {
			createBOUserView.getLblGroupValidateMessage().setValue(
				createBOUserView.getCbbGroup().getErrorMessage().getFormattedHtmlMessage());
		    }
		    createBOUserView.getRow6Validate().setVisible(true);
		}
	    }

	} catch (Exception e) {
	    e.printStackTrace();
	    return false;
	}
	return false;
    }

}
